import urllib3  # pip install urllib3
import sseclient   # pip install sseclient-py
# import io

# def with_urllib3(url, headers):
#     """Get a streaming response for the given event feed using urllib3."""
#     # import urllib3
#     http = urllib3.PoolManager()
#     return http.request('GET', url, preload_content=False, headers=headers)
    # return http.request('POST', url, preload_content=False, headers=headers)


# 第一种方式
def sse_client(url, headers):
    """
    pip install sseclient-py
    """
    # response = with_urllib3(url, headers)
    
    http = urllib3.PoolManager()
    # response = http.request('GET', url, preload_content=False, headers=headers)
    response = http.request('POST', url, preload_content=False, headers=headers)
    client = sseclient.SSEClient(response)
    for event in client.events():
        # print(event)
        print(event.data)
    # 关闭连接
    http.clear()

# 第二种方式，不太可行
# def sse_with_urllib3(url, headers):
#     # response = with_urllib3(url, headers)
    
#     http = urllib3.PoolManager()
#     response = http.request('GET', url, preload_content=False, headers=headers)
#     # 将流式响应转换为迭代器
#     response_stream = response.data

#     # 读取 SSE 事件
#     for line in io.TextIOWrapper(response_stream, encoding='utf-8'):
#         line = line.strip()
#         if line:  # 忽略空行
#             if line.startswith('data:'):
#                 # 提取数据部分
#                 data = line[5:].strip()
#                 print('Received data:', data)
#             elif line.startswith('event:'):
#                 # 提取事件类型
#                 event = line[6:].strip()
#                 print('Received event:', event)
#             elif line.startswith('id:'):
#                 # 提取事件 ID
#                 event_id = line[3:].strip()
#                 print('Received event ID:', event_id)
#             elif line.startswith('retry:'):
#                 # 提取重试时间
#                 retry = int(line[6:].strip())
#                 print('Retry in:', retry, 'ms')
#             else:
#                 print('Unknown line:', line)
    
#     # 关闭连接
#     http.clear()


if __name__ == "__main__":
    url = "http://127.0.0.1:8080/sse2"
    headers = {"Accept": "text/event-stream"}
    sse_client(url, headers)
    # sse_with_urllib3(url, headers)